<?php

require_once 'model/form.class.php';

class Core_Table_Html_Form extends Database_Table
{
	protected $_name = 'core_html_form';

	protected $_rowClass = 'Core_Table_Html_Model_Form';

	function loadFormStructure($formKey)
	{
		$select = $this -> select() -> where('form_key=?', (string)$formKey);

		$form = $this -> fetchRow($select);

		if (!$form)
		{
			return FALSE;
		}

		$table2 = Nuo::getTable('core/html/element');
		$table3 = Nuo::getTable('core/html/data');
		$table = Nuo::getTable('core/html/item');

		$select = $table -> select() -> from(array('item' => $table -> getName()), array(
			'item.item_id',
			'item.is_required',
			'item.parent_id',
			'item.item_label AS label',
			'item.item_key AS name',
			'item.item_extra AS extra'
		)) -> joinLeft(array('ele' => $table2 -> getName()), 'ele.element_id=item.element_id', array('ele.element_key AS type')) -> joinLeft(array('data' => $table3 -> getName()), 'data.data_id=item.data_id', array(
			'data.data_key',
			'data.data_cachable',
		)) -> where('form_id=?', $form -> getId()) -> where('item.is_enabled=1')
		 -> order('item.sort_order ASC');

		// echo $select;

		$tmpRows = $table -> fetchAll($select) -> toArray();
		$rows = array();
		$childs = array();

		/**
		 * process extra to load config to tempRow
		 */
		foreach ($tmpRows as $tmpRow)
		{

			$options = (array)json_decode($tmpRow['extra'], 1);

			$options['label'] = $tmpRow['label'];
			unset($tmpRow['label']);

			$id = $tmpRow['item_id'];
			$parentId = $tmpRow['parent_id'];
			
			$options['require'] =  $tmpRow['is_required'];
			
			if ($tmpRow['data_key'])
			{
				list($plugin, $method) = explode(':', $tmpRow['data_key']);
				$options['multiOptions'] = Nuo::getObject($plugin, 'plugin') -> {$method}();
			}

			$tmpRow['options'] = $options;

			if ($parentId && $parent_id != $id)
			{
				$childs[$id] = $tmpRow;
			}
			else
			{
				$rows[$id] = $tmpRow;
			}
		}

		unset($tmpRows);

		foreach ($childs as $id => $child)
		{
			$parentId = $child['parent_id'];

			if (isset($rows[$parentId]) && $rows[$parentId]['type'] == 'group')
			{
				$rows[$parentId]['options']['children'][$id] = $child;
			}
		}

		$structure['children'] = $rows;
		$structure['title'] = $form -> form_title;
		$structure['desc'] = $form -> description;
		$structure['name'] = $form -> form_key;
		
		return $structure;
	}

}
